package com.huawei.esdk.tp.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

import com.huawei.esdk.platform.common.constants.ESDKErrorCodeConstant;
import com.huawei.esdk.platform.common.exception.SDKException;
import com.huawei.esdk.platform.common.utils.Base64Utils;

public abstract class TPAAUtils
{
    private static final Logger LOGGER = Logger.getLogger(TPAAUtils.class);
    
    /**
     * "Password + random key" SHA256 encrypted. random key is encrypted by
     * BASE64, password is not encrypted
     * 
     * @param password
     * @param randomkey
     * @return
     */
    public static String getEncryptPassword(String password, String randomkey)
        throws SDKException
    {
        LOGGER.debug("getEncryptPassword start");
        byte[] encryptPassword;
        MessageDigest md;
        String ep = null;
        try
        {
            md = MessageDigest.getInstance("SHA-256");
            md.update(password.getBytes("UTF-8"));
            encryptPassword = md.digest();
            
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append(bytesToHexString(encryptPassword));
            String password1 = sBuilder.toString();
            
            sBuilder = new StringBuilder();
            sBuilder.append(bytesToHexString(Base64Utils.getFromBASE64(randomkey)));
            password1 += sBuilder.toString();
            
            md.update(password1.getBytes("UTF-8"));
            encryptPassword = md.digest();
            
            sBuilder.append(bytesToHexString(encryptPassword));
            ep = Base64Utils.encode(encryptPassword);
        }
        catch (NoSuchAlgorithmException e)
        {
            LOGGER.error("", e);
            SDKException ex = new SDKException("");
            ex.setSdkErrCode(ESDKErrorCodeConstant.ERROR_CODE_SYS_ERROR);
            throw ex;
        }
        catch (UnsupportedEncodingException e)
        {
            LOGGER.error("", e);
            SDKException ex = new SDKException("");
            ex.setSdkErrCode(ESDKErrorCodeConstant.ERROR_CODE_SYS_ERROR);
            throw ex;
        }
        LOGGER.debug("getEncryptPassword end");
        return ep;
    }
    
    /**
     * random key generate function, in SMC the random key's number is 16
     * 
     * @return
     */
    public static byte[] generateRandomKey()
    {
        LOGGER.debug("generateRandomKey start");
        byte[] ranArray = new byte[16];
        java.util.Random random = new java.util.Random();
        for (int i = 0; i < 16; i++)
        {
            int randint = random.nextInt();
            ranArray[i] = (byte)(((randint >> 8) * i) & 0xFF);
        }
        LOGGER.debug("generateRandomKey end");
        return ranArray;
    }
    
    /**
     * @param srcArray
     * @return
     */
    public static String bytesToHexString(byte[] srcArray)
    {
        if (null == srcArray || srcArray.length <= 0)
        {
            return null;
        }
        StringBuffer sb = new StringBuffer(srcArray.length);
        
        String temp;
        for (int i = 0; i < srcArray.length; i++)
        {
            temp = Integer.toHexString(0xFF & srcArray[i]);
            if (temp.length() < 2)
                sb.append(0);
            sb.append(temp);
        }
        return sb.toString();
    }
}
